<template>
  <div class="search-container">
        <!-- 标题区域 -->
        <h1 class="text-[clamp(1.8rem,4vw,2.5rem)] font-bold text-gray-800 mb-10 text-center">
            余额查询
        </h1>
        <!-- 查询表单 -->
        <div class="search-content">
                <div class="flex-grow">
                  <label for="tokenInput" class="block text-sm font-medium text-gray-700 mb-1">
                        密钥查询
                    </label>
                  <el-select v-model="selectValue" placeholder="请选择查询类型" size="large">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
                <div class="flex-grow">
                    <div class="relative">
                        <span style="font-size: 20px" class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                            <el-icon><key /></el-icon>
                        </span>
                        <el-input v-model="keyTxt" placeholder="请输入您的密钥" />
                    </div>
                </div>
                <div style="margin-left: 0.4rem">
                    <el-button
                        type="primary"
                        style="font-size:16px;height:48.5px"
                        @click="searchSubmit"
                    >
                        <el-icon><search /></el-icon>
                        <span>查询</span>
                    </el-button>
                </div>
        </div>
        
        <!-- 结果展示区域 -->
        <div id="resultArea" class="w-full max-w-2xl" v-if='searchStatus == 2'>
            <div class="bg-white rounded-xl p-6 card-shadow border-l-4 border-primary">
                <div class="flex items-start gap-4">
                    <div class="text-primary text-2xl mt-1">
                        <el-icon color="rgb(59 130 246)"><success-filled /></el-icon>
                    </div>
                    <div>
                        <h2 class="text-lg font-semibold text-gray-800 mb-2">查询结果</h2>
                        <div v-if="selectValue == 'token'">
                          <p class="text-gray-700 text-lg">余额：{{remainQuota}}单位</p>
                          <p class="text-gray-500 text-sm mt-2">有效期至: {{remainTime}}</p>
                        </div>
                        <div v-else>
                          <p class="text-gray-700 text-lg">状态：{{status}}</p>
                          <p class="text-gray-500 text-sm mt-2" v-if="generateTime">生成时间：{{generateTime}}</p>
                          <p class="text-gray-500 text-sm mt-2" v-if="activateTime">激活时间：{{activateTime}}</p>
                          <p class="text-gray-500 text-sm mt-2" v-if="expireTime">过期时间：{{expireTime}}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 错误提示区域 -->
        <div id="errorArea" class="w-full max-w-2xl" v-if='searchStatus == 3'>
            <div class="bg-white rounded-xl p-6 card-shadow border-l-4 border-red-500">
                <div class="flex items-start gap-4">
                    <div class="text-red-500 text-2xl mt-1">
                        <el-icon><warning-filled /></el-icon>
                    </div>
                    <div>
                        <h2 class="text-lg font-semibold text-gray-800 mb-2">查询失败</h2>
                        <p id="errorMessage" class="text-gray-700">{{errorMessage}}</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 加载状态 -->
        <div id="loadingArea" class="w-full max-w-2xl" v-if='searchStatus == 1'>
            <div class="bg-white rounded-xl p-6 card-shadow flex justify-center items-center">
                <div class="flex items-center gap-3">
                    <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary"></div>
                    <p class="text-gray-700">正在查询，请稍候...</p>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { tokenSearch, checkState } from '@/api/remainApi'

const router = useRouter()

const selectValue = ref('token');
const options = [
  {
    value: 'token',
    label: '大模型token查询',
  },
  {
    value: 'deeplx',
    label: 'deeplx token查询',
  }
]

const keyTxt = ref('');

const searchStatus = ref(0); // 0 未搜索  1 正在搜索  2 结果成功  3 结果失败

const errorMessage = ref('');

const remainQuota = ref(0);
const remainTime = ref(0);
const generateTime = ref(0);
const activateTime = ref(0);
const expireTime = ref(0);
const status = ref(0);

onMounted(() => {
  document.title = '余额查询';
})

// 查询
const searchSubmit = () => {
  if (!keyTxt.value) {
    ElMessage.error('请输入您的密钥')
  } else {
    searchStatus.value = 1;
    if (selectValue.value == 'token') {
      // token类型
      searchTokenFn()
    } else {
      // deeplx token
      searchDeeplxFn();
    }
  }
}
async function searchTokenFn() {
  try {
    const res = await tokenSearch(keyTxt.value);
    if (res.success) {
      const data = res.data || [];
      if(data.length === 0 || data[0].remain_quota === undefined) {
        searchStatus.value = 3;
        errorMessage.value = '返回数据格式不正确，无法计算余额';
      } else {
        searchStatus.value = 2;
        const remainTxt = data[0].remain_quota;
        remainQuota.value = (remainTxt * 100).toFixed(0);
        const time = data[0].expired_time;
        remainTime.value = time!=-1?convertTimestamp(time):'无'
      }
    } else {
      searchStatus.value = 0;
      ElMessage.error(res.message);
    }
  } catch (error) {
    searchStatus.value = 0;
    ElMessage.error(error)
  }
}
async function searchDeeplxFn() {
  try {
    const res = await checkState(keyTxt.value);
    if (res.success) {
      if (res.result) {
        searchStatus.value = 2;
        generateTime.value = res.result.generateTime || 0;
        activateTime.value = res.result.activateTime || 0;
        expireTime.value = res.result.expireTime || 0;
        if (res.result.status === 0) {
          status.value = '未激活'
        } else if (res.result.status === 1) {
          status.value = '已激活'
        } else {
          status.value = '已过期'
        }
      } else {
        searchStatus.value = 3;
        errorMessage.value = '密钥不正确，请重新输入';
      }
    } else {
      searchStatus.value = 0;
      ElMessage.error(res.message);
    }
  } catch (error) {
    searchStatus.value = 0;
    ElMessage.error(error)
  }
}

const convertTimestamp = (timestamp) => {
  // 创建Date对象，注意JavaScript时间戳是毫秒级的，需要乘以1000
  const date = new Date(timestamp * 1000);
  
  // 获取年份
  const year = date.getFullYear();
  
  // 获取月份，注意月份从0开始，需要加1，并且不足两位补0
  const month = String(date.getMonth() + 1).padStart(2, '0');
  
  // 获取日期，不足两位补0
  const day = String(date.getDate()).padStart(2, '0');
  
  // 获取小时，不足两位补0
  const hours = String(date.getHours()).padStart(2, '0');
  
  // 获取分钟，不足两位补0
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  // 获取秒钟，不足两位补0
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  // 拼接成指定格式
  const res = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  return res;
}
            
</script>

<style scoped>
.search-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  flex-grow: 1;
  height: 100vh;
  background-color: rgb(249 250 251);
}
.card-shadow {
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
.search-content {
  display: flex;
  width: 100%;
  max-width: 42rem;
  padding: 2rem;
  border-radius: 0.75rem;
  background: #fff;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
  align-items: flex-end;
  margin-bottom: 2rem;
}
.border-primary {
    border-color: rgb(59 130 246);
}
::v-deep .el-select--large .el-select__wrapper {
  min-height: 48.5px;
  margin-right: 0.4rem;
}
::v-deep .el-input {
  height: 48.5px;
}
</style>